//
//  WordsDictData.m
//  KidReading
//
//  Created by telen on 14/12/31.
//  Copyright (c) 2014年 刘赞黄Telen. All rights reserved.
//

#import "WordsDictData.h"
#import "ConstDefine.h"

@implementation WordsDictData
{
    NSString* dict_lang;
}

static WordsDictData* wordsDictDataSingle = nil;

+ (WordsDictData *)shareSingle
{
    if (!wordsDictDataSingle) {
        wordsDictDataSingle = [[WordsDictData alloc] init];
    }
    return wordsDictDataSingle;
}

- (instancetype)init
{
    if (self = [super init]) {
        delegateArr = [[NSMutableArray alloc] initWithCapacity:0];
    }
    return self;
}

- (NSMutableDictionary*)getDictForBook:(NSInteger)bookid;
{
    NSMutableDictionary* dict = nil;
    NSString *SystemSave = [DataProcessing wordDictPathForBookID:bookid];
#if __Debug_CloseAES == 0
    NSData* data = [[NSData alloc] initWithContentsOfFile:SystemSave];
    data = [data AES256DecryptWithKey:__AESKey];//解密
    @try {
        dict = [NSKeyedUnarchiver unarchiveObjectWithData:data];
    }
    @catch (NSException *exception) {
        NSLog(@"%@",exception);
    }
    @finally {
        
    }
    
#else
    dict = [[NSMutableDictionary alloc] initWithContentsOfFile:SystemSave];
#endif
    if (!dict) {
        dict = [[NSMutableDictionary alloc] initWithCapacity:0];
        [dict setObject:[NSNumber numberWithInteger:bookid] forKey:@"book"];
    }
    //
    return dict;
}

- (void)saveDict:(NSDictionary*)dict forBook:(NSInteger)bookid
{
    NSString *SystemSave = [DataProcessing wordDictPathForBookID:bookid];
#if __Debug_CloseAES == 0
    NSData* data = [NSKeyedArchiver archivedDataWithRootObject:dict];
    data = [data AES256EncryptWithKey:__AESKey];//加密
    [data writeToFile:SystemSave atomically:YES];
#else
    [dict writeToFile:SystemSave atomically:YES];
#endif
}

- (void)setGetWordsDelegate:(id<WordsDictDataDelegate>)delgate_
{
    NSValue* value = [NSValue valueWithNonretainedObject:delgate_];
    [delegateArr addObject:value];
}

- (void)unSetGetWordsDelegate:(id<WordsDictDataDelegate>)delgate_
{
    NSArray* arr = [NSArray arrayWithArray:delegateArr];
    for (NSValue* value in arr) {
        id<WordsDictDataDelegate> obj = [value nonretainedObjectValue];
        if (obj == delgate_) {
            [delegateArr removeObject:value];
            break;
        }
    }
}

- (NSString*)words_Keys_From_words:(NSString *)words pinYin:(NSString *)py phrase:(NSArray *)phraseArr phraseIdx:(NSInteger)phraseIdx isEnglishWord:(BOOL)en contryCode:(NSString*)ccode
{
    if (en) {
        NSString* keys = [phraseArr componentsJoinedByString:@","];
        return [NSString stringWithFormat:@"%@_%@_%@",ccode.lowercaseString,keys,@(phraseIdx)];
    }else{
        return [NSString stringWithFormat:@"%@_%@_%@",ccode.lowercaseString,words,py];
    }
}

- (void)getwordsInfo_bookID:(NSInteger)bookid bookOid:(NSInteger)bookOid words:(NSString *)words pinYin:(NSString *)py phrase:(NSArray *)phraseArr phraseIdx:(NSInteger)phraseIdx isEnglishWord:(BOOL)en
{
    NSString* keyBook = @"book";
    NSString* countryCode = [CacheData shareSingle].getUserLoginInfo.country_code;
    if (!countryCode) {
        countryCode = @"cn";
    }
    NSString* keyWords = [self words_Keys_From_words:words pinYin:py phrase:phraseArr phraseIdx:phraseIdx isEnglishWord:en contryCode:countryCode];
    NSString* keyWords_date = [NSString stringWithFormat:@"%@_date",keyWords];
    NSNumber* bid = [mDict objectForKey:keyBook];
    nullToNil(bid);
    if (!mDict || [bid integerValue] != bookid) {
        mDict = [self getDictForBook:bookid];
    }
    NSDictionary* throughDict = @{keyBook:@(bookid),@"word":words,@"py":py,@"phrase":phraseArr,@"phrase_idx":@(phraseIdx),@"en":@(en),@"region_code":countryCode};
    //[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInteger:bookid],keyBook,words,@"word",py,@"py", nil];
    //
    BOOL needNet = NO;
    NSDictionary* infoDict = [mDict objectForKey:keyWords];
    nullToNil(infoDict);
    if (infoDict) {
        NSDate* dateZ = [mDict objectForKey:keyWords_date];
        nullToNil(dateZ);
        if (!dateZ
            || [DataProcessing isDictOutTime:dateZ]) {//字典过去判断
            needNet = YES;
        }else{
            for (NSValue* value in delegateArr) {
                id<WordsDictDataDelegate> delegate = [value nonretainedObjectValue];
                if (delegate && [delegate respondsToSelector:@selector(wordsDictData_DidGetInfo:forWords:andPinyin:)]) {
                    [delegate wordsDictData_DidGetInfo:infoDict forWords:words andPinyin:py];
                }
            }
            //读音离线
            NSArray* arr = [infoDict objectForKey:@"duyin"];
            nullToNil(arr);
            if(arr)[self getSounds:arr fromNetOnly:NO throughDict:throughDict];
        }
    }else{
        needNet = YES;
    }
    if(needNet){
        NSError* error;
        NSData* phraseData = [NSJSONSerialization dataWithJSONObject:phraseArr options:NSJSONWritingPrettyPrinted error:&error];
        NSString* phrase = [[NSString alloc] initWithData:phraseData encoding:NSUTF8StringEncoding];
        NSDictionary* dict = [NSDictionary dictionaryWithObjectsAndKeys:@"ios",@"pf",@"dict",@"op",@(bookid),@"pid",words,@"word",py,@"py",@(bookOid),@"original_id",phrase,@"phrase", @(phraseIdx),@"phrase_idx",countryCode,@"region_code",nil];
        //NSLog(@"%@-->>%@ -->%@ -->>>>%@", error,dict,phraseArr,phraseData);
        [[NetRequest shareSingle] askNet:__URL_PortBooks_Dict andBaseUrl:__Ser3_0_URL_Base_ refsDict:dict delegate:self withThroughDict:throughDict];
    }
}

- (void)getSounds:(NSArray*)soundArr fromNetOnly:(BOOL)yn throughDict:(NSDictionary*)throughDict;
{
    if (!soundArr || soundArr.count == 0) {
        return;
    }
    BOOL isDownAll = YES;
    NSSet* set = [NSSet setWithArray:soundArr];
    soundArr = [set allObjects];
    for (NSString* path in soundArr) {
        if(path.length==0){
            NSLog(@"soundPath Empty");
            isDownAll = NO;
            continue;
        }
        NSString* fileName = [[path componentsSeparatedByString:@"/"] lastObject];
        NSString* urlstr = [DataProcessing fullDuyinUrl:path];
        NSString* localpath = [[DataProcessing wordDictSoundPath] stringByAppendingPathComponent:fileName];
        if ([[NSFileManager defaultManager] fileExistsAtPath:localpath]){
            if (!yn){
                continue;
            }
            else{
                [[NSFileManager defaultManager] removeItemAtPath:localpath error:nil];
            }
        }
        isDownAll = NO;
        NSString* localpath_downing = [localpath stringByAppendingString:@".tl"];
        //
        JRASIHTTPRequest* asihttprequest = [JRASIHTTPRequest requestWithURL:[NSURL URLWithString:urlstr]];
        [asihttprequest setTemporaryFileDownloadPath:localpath_downing];
        [asihttprequest setDownloadDestinationPath:localpath];
        [asihttprequest setUserInfo:[NSDictionary dictionaryWithObjectsAndKeys:soundArr,@"soundArr",throughDict,__throughDict__, nil]];
        [asihttprequest setDelegate:self];
        [asihttprequest setDownloadProgressDelegate:self];
        [asihttprequest setAllowResumeForFileDownloads:NO];//开关断点下载
        [asihttprequest startAsynchronous];
    }
    for (NSValue* value in delegateArr) {
        id<WordsDictDataDelegate> delegate = [value nonretainedObjectValue];
        if (isDownAll && delegate && [delegate respondsToSelector:@selector(wordsDictData_DidGetSound_forWords:andPinyin:)]) {
            NSString* words = [throughDict objectForKey:@"word"];
            nullToNil(words);
            NSString* py = [throughDict objectForKey:@"py"];
            nullToNil(py);
            [delegate wordsDictData_DidGetSound_forWords:words andPinyin:py];
        }
    }
}

- (void)playSounds:(NSArray *)soundArr withSign:(NSString *)sign
{
    BOOL isDownAll = YES;
    NSMutableArray* mArr = [[NSMutableArray alloc] initWithCapacity:0];
    for (NSString* path in soundArr) {
        if(path.length==0)
        {
            isDownAll = NO;
            NSLog(@"SoudPath Error :%@",path);
            continue;
        }
        NSString* fileName = [[path componentsSeparatedByString:@"/"] lastObject];
        NSString* localpath = [[DataProcessing wordDictSoundPath] stringByAppendingPathComponent:fileName];
        if ([[NSFileManager defaultManager] fileExistsAtPath:localpath]){
            [mArr addObject:localpath];
            continue;
        }
        isDownAll = NO;
        break;
    }
    if (isDownAll && mArr.count > 0) {
        [[TLSoundPlayer shareSingle] playSoundArr:mArr andDelegate:self withSign:sign];
    }
}

#define __Dict_Lang @"joy_Dict_lang"
- (NSString *)getDict_Lang
{
    if (dict_lang == nil) {
        dict_lang = [[NSUserDefaults standardUserDefaults] objectForKey:__Dict_Lang];
        if (dict_lang == nil) {
            NSArray *languages = [[NSUserDefaults standardUserDefaults] objectForKey:@"AppleLanguages"];
            NSString* lang = [languages firstObject];
            if ([lang hasPrefix:@"en"]) {
                return @"en";
            }
            if ([lang hasPrefix:@"zh"]) {
                return @"cn";
            }
        }
    }
    return dict_lang;
}

- (void)setDict_Lang:(NSString *)lang
{
    if (lang != nil && [lang isKindOfClass:[NSString class]]) {
        dict_lang = lang;
        [[NSUserDefaults standardUserDefaults] setObject:dict_lang forKey:__Dict_Lang];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
}

#pragma mark- delegate

- (void)netRequestFailed:(NSDictionary *)dict
{
//    NSLog(@"Dict Net Get Error: %@",dict);
    //
    NSDictionary* throughDict = [dict objectForKey:__throughDict__];
    nullToNil(throughDict);
    NSString* words = [throughDict objectForKey:@"word"];
    nullToNil(words);
    NSString* py = [throughDict objectForKey:@"py"];
    nullToNil(py);
    NSArray* phraseArr = [throughDict objectForKey:@"phrase"];
    nullToNil(phraseArr);
    NSNumber* phraseIdxNum = [throughDict objectForKey:@"phrase_idx"];
    nullToNil(phraseIdxNum);
    NSNumber* enNum = [throughDict objectForKey:@"en"];
    nullToNil(enNum);
    //
    NSString* countryCode = [CacheData shareSingle].getUserLoginInfo.country_code;
    if (!countryCode) {
        countryCode = @"cn";
    }
    NSString* keyWords = [self words_Keys_From_words:words pinYin:py phrase:phraseArr phraseIdx:phraseIdxNum.integerValue isEnglishWord:enNum.boolValue contryCode:countryCode];
    NSDictionary* infoDict = [mDict objectForKey:keyWords];
    nullToNil(infoDict);
    for (NSValue* value in delegateArr) {
        id<WordsDictDataDelegate> delegate = [value nonretainedObjectValue];
        if (delegate && [delegate respondsToSelector:@selector(wordsDictData_DidGetInfo:forWords:andPinyin:)]) {
            [delegate wordsDictData_DidGetInfo:infoDict forWords:words andPinyin:py];
        }
    }
    //读音离线
    NSArray* arr = [infoDict objectForKey:@"duyin"];
    nullToNil(arr);
    if(arr)[self getSounds:arr fromNetOnly:NO throughDict:throughDict];
    
    //百度统计 取词失败
    [NSObject msgToClassName:@"TLMobStat" menthed:@"logEvent:eventLabel:" refs:@[FI_main,@"取词失败"] needReturnValue:NO];
}

- (void)netRequestFinished:(NSDictionary *)dict
{
    NSString* keyBook = @"book";
    //
    NSDictionary* infoDict = [dict objectForKey:__NetBack__];
    nullToNil(infoDict);
    NSDictionary* throughDict = [dict objectForKey:__throughDict__];
    nullToNil(throughDict);
    NSNumber* bidt = [throughDict objectForKey:keyBook];
    nullToNil(bidt);
    NSInteger bookid = [bidt integerValue];
    NSString* words = [throughDict objectForKey:@"word"];
    nullToNil(words);
    NSString* py = [throughDict objectForKey:@"py"];
    nullToNil(py);
    NSArray* phraseArr = [throughDict objectForKey:@"phrase"];
    nullToNil(phraseArr);
    NSNumber* phraseIdxNum = [throughDict objectForKey:@"phrase_idx"];
    nullToNil(phraseIdxNum);
    NSNumber* enNum = [throughDict objectForKey:@"en"];
    nullToNil(enNum);
    //
    NSString* countryCode = [CacheData shareSingle].getUserLoginInfo.country_code;
    if (!countryCode) {
        countryCode = @"cn";
    }
    NSString* keyWords = [self words_Keys_From_words:words pinYin:py phrase:phraseArr phraseIdx:phraseIdxNum.integerValue isEnglishWord:enNum.boolValue contryCode:countryCode];
    NSString* keyWords_date = [NSString stringWithFormat:@"%@_date",keyWords];
    //
    NSMutableDictionary* mdic = nil;
    NSNumber* bid = [mDict objectForKey:keyBook];
    nullToNil(bid);
    if (mDict && [bid integerValue] == bookid) {
        mdic = mDict;
    }
    if (!mdic) {
        mdic = [self getDictForBook:bookid];
    }
    [mdic setObject:infoDict forKey:keyWords];
    [mdic setObject:[NSDate date] forKey:keyWords_date];
    [self saveDict:mdic forBook:bookid];
    //读音离线
    NSArray* arr = [infoDict objectForKey:@"duyin"];
    nullToNil(arr);
    if(arr)[self getSounds:arr fromNetOnly:YES throughDict:throughDict];
    
    //
    for (NSValue* value in delegateArr) {
        id<WordsDictDataDelegate> delegate = [value nonretainedObjectValue];
        if (delegate && [delegate respondsToSelector:@selector(wordsDictData_DidGetInfo:forWords:andPinyin:)]) {
            [delegate wordsDictData_DidGetInfo:infoDict forWords:words andPinyin:py];
        }
    }
}

//downMp3
- (void)requestFailed:(JRASIHTTPRequest *)request
{
#if __Debug_Net || __Debug_Net_Error
    NSString* str1 = [request responseString];
    NSString* str2 = [request responseStatusMessage];
    NSLog(@"requestStatus:%@  requestMsg:%@",str2,str1);
    NSURL* url = [request url];
    NSLog(@"requestFailed:errorURL: %@",url);
    NSLog(@"error: %@",request.error);
#endif
}
- (void)requestFinished:(JRASIHTTPRequest *)request
{
    NSDictionary* userInfo = [request userInfo];
    NSDictionary* throughDict = [userInfo objectForKey:__throughDict__];
    nullToNil(throughDict);
    NSArray* soundArr = [userInfo objectForKey:@"soundArr"];
    nullToNil(soundArr);
    BOOL isDownAll = YES;
    for (NSString* path in soundArr) {
        if(path.length==0)
        {
            isDownAll = NO;
            NSLog(@"SoudPath Error :%@",path);
            continue;
        }
        NSString* fileName = [[path componentsSeparatedByString:@"/"] lastObject];
        NSString* localpath = [[DataProcessing wordDictSoundPath] stringByAppendingPathComponent:fileName];
        if (![[NSFileManager defaultManager] fileExistsAtPath:localpath]){
            isDownAll = NO;
            break;
        };
    }
    for (NSValue* value in delegateArr) {
        id<WordsDictDataDelegate> delegate = [value nonretainedObjectValue];
        if (isDownAll && delegate && [delegate respondsToSelector:@selector(wordsDictData_DidGetSound_forWords:andPinyin:)]) {
            NSString* words = [throughDict objectForKey:@"word"];
            nullToNil(words);
            NSString* py = [throughDict objectForKey:@"py"];
            nullToNil(py);
            [delegate wordsDictData_DidGetSound_forWords:words andPinyin:py];
            //debug
            //        [self playSounds:soundArr withSign:words];
        }
    }
}

- (void)tlSoundPlayerDidFinishPlayingArr:(NSArray *)fullPathArr withSign:(NSString *)sign
{
    for (NSValue* value in delegateArr) {
        id<WordsDictDataDelegate> delegate = [value nonretainedObjectValue];
        if (delegate && [delegate respondsToSelector:@selector(wordsDictData_DidFinishPlaySounds:withSign:)]) {
            [delegate wordsDictData_DidFinishPlaySounds:fullPathArr withSign:sign];
        }
    }
}

- (void)tlSoundPlayerDidStartPlayingArr:(NSArray *)fullPathArr withSign:(NSString *)sign
{
    for (NSValue* value in delegateArr) {
        id<WordsDictDataDelegate> delegate = [value nonretainedObjectValue];
        if (delegate && [delegate respondsToSelector:@selector(wordsDictData_DidStartPlaySounds:withSign:)]) {
            [delegate wordsDictData_DidStartPlaySounds:fullPathArr withSign:sign];
        }
    }
}

@end
